package com.zyh.server.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author: zyh
 * @Date: 2024-11-13-10:47
 * @Description
 */
@Component
public class RedisUtil {
	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 将key-value存入到redis数据库中
	 *
	 * @param key
	 * @param value
	 * @param timeout 分钟
	 */
	public void saveObj(String key, Object value, long timeout) {
		redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.MINUTES);
	}

	public void saveObj(String key, Object value, long timeout, TimeUnit timeUnit) {
		redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
	}

	/**
	 * 根据key获取value
	 *
	 * @param key
	 *
	 * @return
	 */
	public Object getObj(String key) {
		return redisTemplate.opsForValue().get(key);
	}

	/**
	 * 根据key删除value
	 *
	 * @param key
	 */
	public void deleteObj(String key) {
		redisTemplate.delete(key);
	}

	/**
	 * 设置key的缓存时间 (用于续签)
	 */
	public boolean expire(String key, long timeout) {
		try {
			if (timeout > 0) {
				redisTemplate.expire(key, timeout, TimeUnit.MINUTES);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();//打印错误信息
			return false;
		}
	}

	public boolean expire(String key, long timeout, TimeUnit timeUnit) {
		try {
			if (timeout > 0) {
				redisTemplate.expire(key, timeout, timeUnit);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();//打印错误信息
			return false;
		}
	}

	/**
	 * 根据key 获取过期时间
	 *
	 * @param key
	 *
	 * @return
	 */
	public long getExpire(String key) {
		Long time = redisTemplate.getExpire(key);
		return time == null ? 0 : time;
	}

	/**
	 * 判断缓存中是否存在此key
	 */
	public boolean hasKey(String key) {
		return redisTemplate.hasKey(key);
	}
}
